package com.xishu.util;

import com.google.common.collect.Lists;
import com.xishu.entity.AbstractEntity;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.beanutils.BeanUtils;

import java.util.*;
import java.util.stream.Collectors;

public class CollectionUtil implements Tools {
    private static CollectionUtil instance = new CollectionUtil();

    private CollectionUtil() {
    }

    public static CollectionUtil getInstance() {
        return instance;
    }

    /**
     * 获取前N个
     *
     * @param list
     * @param n
     * @return
     */
    public <T extends Object> List<T> take(List<T> list, int n) {
        if (isEmpty(list)) {
            return new ArrayList<>();
        }

        if (list.size() <= n) {
            return list;
        }


        return new ArrayList(list.subList(0, n));
    }

    /**
     * 获取最后一个元素
     *
     * @param list
     * @return
     */
    public <T extends Object> T last(List<T> list) {
        if (isEmpty(list)) {
            return null;
        }

        return list.get(list.size() - 1);
    }

    /**
     * 获取第一个元素
     *
     * @param list
     * @return
     */
    public <T extends Object> T first(List<T> list) {
        if (isEmpty(list)) {
            return null;
        }

        return list.get(0);
    }


    /**
     * 按照大小来分组
     *
     * @param list
     * @param groupSize
     * @return
     */
    public List<List> partition(List list, int groupSize) {
        return Lists.partition(list, groupSize);
    }

    /**
     * 将entryList 转化成Map
     *
     * @param entryList
     * @return
     */
    public Map entryListToMap(List<Map.Entry<String, Object>> entryList) {
        Map<String, Object> map = new HashMap<>();

        for (Map.Entry<String, Object> stringObjectEntry : entryList) {
            map.put(stringObjectEntry.getKey(), stringObjectEntry.getValue());
        }

        return map;
    }

    /**
     * 将对象转化成map
     *
     * @param object
     * @return
     */
    public Map beanToMap(Object object) {
        BeanMap beanMap = new BeanMap(object);
        HashMap<String, Object> map = new HashMap<String, Object>(beanMap);
        map.remove("class");

        return map;
    }

}
